package io.xxx.omni.osc.sdk

import com.alibaba.fastjson.JSONObject
import io.xxx.omni.osc.domain.Store
import org.apache.commons.codec.digest.DigestUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.web.client.RestTemplate
import org.springframework.web.util.UriComponentsBuilder
import java.util.*

@Component
class AkcClient {

    @Autowired
    private lateinit var restTemplate: RestTemplate

    private val httpUrl = "https://openapi.aikucun.com"

    fun execute(store: Store, path: String, request: Map<String, Any>): JSONObject {
        val authorization = store.authorization
        val signMap = TreeMap(request)
        signMap["appid"] = authorization["appid"]
        signMap["noncestr"] = "1"
        signMap["erp"] = "Winner-ERP"
        signMap["erpversion"] = "1.0"
        signMap["timestamp"] = System.currentTimeMillis().toString()
        val urlBuilder = UriComponentsBuilder
            .fromHttpUrl(httpUrl)
            .path(path)
        signMap.forEach { urlBuilder.queryParam(it.key, it.value) }
        signMap["appsecret"] = authorization["appsecret"]
        val sign = DigestUtils.sha1Hex(signMap.entries.joinToString("&"))
        urlBuilder.queryParam("sign", sign)
        val url = urlBuilder.build(false).toUriString()
        return restTemplate.getForEntity(url, JSONObject::class.java).body!!
    }
}